#include "stm32f10x.h"                  // Device header
int16_t RXDataPacket[100];
int8_t RXFlag;
//串口初始化
void Serial_Init(void)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	
	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_IPU;
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_10;
	GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStruct);
	
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AF_PP;
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_9;
	GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStruct);
	
	USART_InitTypeDef USART_InitStruct;
	USART_InitStruct.USART_BaudRate=9600;
	USART_InitStruct.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
	USART_InitStruct.USART_Mode=USART_Mode_Tx|USART_Mode_Rx;
	USART_InitStruct.USART_Parity=USART_Parity_No;
	USART_InitStruct.USART_StopBits=USART_StopBits_1;
	USART_InitStruct.USART_WordLength=USART_WordLength_8b;
	USART_Init(USART1,&USART_InitStruct);
	
	USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
	
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	NVIC_InitTypeDef NVIC_InitStruct;
	NVIC_InitStruct.NVIC_IRQChannel=USART1_IRQn;
	NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=1;
	NVIC_InitStruct.NVIC_IRQChannelSubPriority=1;
	NVIC_Init(&NVIC_InitStruct);
	
	USART_Cmd(USART1,ENABLE);
}

void SendByte(uint8_t Byte)
{
	USART_SendData(USART1,Byte);
	while(USART_GetFlagStatus(USART1,USART_FLAG_TXE)==RESET);
}

void SendString(char* String)
{
	uint8_t i=0;
	for(i=0;String[i]!='\0';i++)
	{
		SendByte(String[i]);
	}
}
int8_t Get_RXFlag()
{
	if(RXFlag==1)
	{
		RXFlag=0;
		return 1;
	}
	
	return 0;
}

void USART1_IRQHandler()
{
	uint16_t RXState=0;
	uint16_t pRXPacket=0;
	if(USART_GetITStatus(USART1,USART_IT_RXNE)==SET)
	{
		if(RXState==0)
		{
			if(USART_ReceiveData(USART1)=='@')
			{
				RXState=1;
			}
		}
		else if(RXState==1)
		{
			if(USART_ReceiveData(USART1)=='\r')
			{
				RXState=2;
			}
			else
			{
				RXDataPacket[pRXPacket]=USART_ReceiveData(USART1);
				pRXPacket++;
			}

		}
		else if(RXState==2)
		{
			if(USART_ReceiveData(USART1)=='\r')
			{
				RXState=0;
				RXDataPacket[pRXPacket]='\0';
				RXFlag=1;
			}
		}
		
		USART_ClearITPendingBit(USART1,USART_IT_RXNE);
	}
	
	
}
